package jdklearning.concurrent.future;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author shenenlu 2021年03月10日 上午11:28:29
 */
public class BaseCompletableFuture {

    public static CompletableFuture<Integer> getAndComplete(){
        final CompletableFuture<Integer> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            future.complete(5);
        }).start();
        return future;
    }


    public static CompletableFuture<Integer> getAndCompleteException(){
        final CompletableFuture<Integer> future = new CompletableFuture<>();
        new Thread(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            future.completeExceptionally(new RuntimeException("exception"));
        }).start();
        return future;
    }



    public static void baseCompletableFuture() throws ExecutionException, InterruptedException {
        // 创建一个带result的CompletableFuture
        CompletableFuture<String> future = CompletableFuture.completedFuture("result");
        future.get();
        // 默认创建的CompletableFuture是没有result的，这时调用future.get()会一直阻塞下去知道有result或者出现异常
        future = new CompletableFuture<>();
        try {
            future.get(1, TimeUnit.SECONDS);
        } catch (Exception e) {
            // no care
        }
    }


    public static void sds(){
        // 使用示例
        CompletableFuture.supplyAsync(() -> {
            System.out.println("hello world");
            return "result";
        }).whenCompleteAsync((result, e) -> {
            System.out.println(result + " " + e);
        }).exceptionally((e) -> {
            System.out.println("exception " + e);
            return "exception";
        });
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        CompletableFuture<Integer> future = getAndComplete();
        CompletableFuture<Integer> future = getAndCompleteException();
        System.out.println(future.get());

//        baseCompletableFuture();
    }
}
